<?php
/**
 *
 * 版权所有：安德玛(underArmour)
 * 作    者：1554324405@qq.com
 * 日    期：2020-05-20
 * 版    本：1.0.0
 * 功能说明：会员收益控制器。
 *
 **/

namespace Admin\Controller;

class OrderController extends ComController
{
    /**
     * 列表
     */
    public function index()
    {
        $key = I('get.keyword','','htmlspecialchars');
        $status = I('get.status','','htmlspecialchars');
        $pay_id = I('get.pay_id','','htmlspecialchars');
        $pay_date = I('get.pay_date','','htmlspecialchars');
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        $field = I('get.field','','htmlspecialchars');
        $sort = I('get.sort','','htmlspecialchars');
        $m = M('user_level_buy');
        
        if($status){
            if($status == -1){
                $where['a.status'] = 0;
            }else{
                $where['a.status'] = $status;
            }
        }
        
        if($pay_id){
            $where['a.pay_id'] = $pay_id;
        }
        
        if($pay_date){
            $t_start = strtotime($pay_date.' 00:00:00');
            $t_end = strtotime($pay_date.' 23:59:59');
            $where['a.finish_t'] = array('between',array($t_start,$t_end));
        }
        
        if($key){
            $where_bear['_logic'] = 'or';
            $where_bear['a.order_no'] = array('like','%'.$key.'%');
            $where_bear['b.nickname'] = array('like','%'.$key.'%');
            $where['_complex'] = $where_bear;
        }
        
        
        $sortSql = "a.id desc";
        if($field and $sort){
            if($field == 'nickname'){
                $sortSql = "b.".$field." ".$sort;
            }else{
                $sortSql = "a.".$field." ".$sort;
            }
        }
        
        $pagesize =20;#每页数量
        $offset = $pagesize * ($p - 1);//计算记录偏移量
        $count = $m
                   ->alias("a")
                   ->join("LEFT JOIN ".C('DB_PREFIX')."user b on a.uid=b.id")
                   ->where($where)->count();
        $list = $m
                   ->alias("a")
                   ->join("LEFT JOIN ".C('DB_PREFIX')."user b on a.uid=b.id")
                   ->field('a.*,b.nickname')
                   ->order($sortSql)
                   ->where($where)
                   ->limit($offset . ',' . $pagesize)
                   ->select();
        foreach ($list as $k=>&$v){
            // 会员等级
            $user_level = M('user_level')->where('id='.$v['level_id'])->field('title')->find();
            $list[$k]['level'] = $user_level['title'];
            // 支付方式
            $pay_type = M('pay_type')->where(array('id'=>$v['pay_id']))->field('name')->find();
            $list[$k]['pay_name'] = $pay_type['name'];
        }
        $page = new \Think\Page($count, $pagesize);
        $page = $page->show();
        //支付方式
        $pay_type_list = M('pay_type')->order('o asc')->select();
        $this->assign('pay_type_list',$pay_type_list);
        $this->assign('list', $list);
        $this->assign('page', $page);
        $this->assign('status',$status);
        $this->assign('p',$p);
        $this->assign('pay_id',$pay_id);
        $this->assign('field',$field);
        $this->assign('sort',$sort);
        $this->display();  
    }
    
    /**
     * 修改
     */
    public function update()
    {
        $id = I('id');
        $p = isset($_GET['p']) ? intval($_GET['p']) : '1';
        if(!$id){
            $this->error('传参为空！');
        }
        if(IS_POST)
        {
            $data['status'] = I('post.status',2,'htmlspecialchars');
            if($data['status'] == 2){
                $data['finish_t'] = time();
                $data['pay_id'] = 2;
            }
            $res = M('user_level_buy')->where('id='.$id)->data($data)->save();
            if($res){
                addlog('修改会员收益为支付状态，ID：'.$id);
                //推荐奖励
                $this->getReward($id);
                //更新用户等级相关信息
                $this->updateUserLevelInfo($id);
                $this->success('修改成功',U('index',array('p'=>$p)));
            }else{
                $this->error('操作失败，请稍后再试！');
            }
        }
        else
        {
            $vo = M('user_level_buy')->where('id='.$id)->find();
            $user_info = M('user')->where('id='.$vo['uid'])->field('nickname')->find();
            $vo['nickname'] = $user_info['nickname'];
            // 会员等级
            $user_level = M('user_level')->where('id='.$vo['level_id'])->field('title')->find();
            $vo['level'] = $user_level['title'];
            // 支付方式
            $pay_type = M('pay_type')->where(array('id'=>$vo['pay_id']))->field('name')->find();
            $vo['pay_name'] = $pay_type['name'];
            // 支付凭证
            if($vo['status'] != 0 and $vo['pz']){
                $this->assign('pz_arr',explode(',', $vo['pz']));
            }
            $this->assign('vo',$vo);
            $this->display('form');
        }
    }
    
    /**
     * 根据订单id获取推荐奖励
     * @param string $order_no
     */
    private function getReward($order_id=0)
    {
        $order_info = M('user_level_buy')->where('id='.$order_id)->find();
        $money = floatval($order_info['money']);
        $uid = $order_info['uid'];
        // 一级推介用户奖励逻辑
        $first_pid_info = M('user')->where('id='.$uid)->field('pid')->find();
        if($first_pid_info['pid']){
            $first_user_info = M('user')->where('id='.$first_pid_info['pid'])->find();
            if($first_user_info['status'] == 1 && strtotime($first_user_info['expri_day']) > time()){
                // 计算一级推介用户的用户等级及一级推荐奖励
                $first_user_level_info = M('user_level')->where('id='.$first_user_info['level_id'])->field('jiangli_1')->find();
                $percent = intval($first_user_level_info['jiangli_1']);
                if($percent > 0){
                    // 插入奖励记录
                    $jl_price = round($money * $percent / 100,2);
                    //更新余额
                    M('user')->where('id='.$first_user_info['id'])->setInc('money',$jl_price);
                    //插入收益记录
                    $income_data = array(
                        'money'=>$jl_price,
                        'type'=>4,
                        't'=>time(),
                        'remark'=>'一级用户推荐奖励'.$jl_price.'元',
                        'uid'=>$first_user_info['id']
                    );
                    M('user_income')->data($income_data)->add();
                    // 加入消息通知
                    M('user_message')->data(array('uid'=>$first_user_info['id'],'content'=>'一级用户推荐奖励'.$jl_price.'元','t'=>time(),'type'=>2))->add();
                }
            } 
            // 二级推介用户奖励逻辑
            if($first_user_info['pid']){
                $second_user_info = M('user')->where('id='.$first_user_info['pid'])->find();
                if($second_user_info['status'] == 1 && strtotime($second_user_info['expri_day']) > time()){
                    // 计算二级推介用户的用户等级及二级推荐奖励
                    $second_user_level_info = M('user_level')->where('id='.$second_user_info['level_id'])->field('jiangli_2')->find();
                    $percent = intval($second_user_level_info['jiangli_2']);
                    if($percent > 0){
                        // 插入奖励记录
                        $jl_price = round($money * $percent / 100,2);
                        //更新余额
                        M('user')->where('id='.$second_user_info['id'])->setInc('money',$jl_price);
                        //插入收益记录
                        $income_data = array(
                            'money'=>$jl_price,
                            'type'=>5,
                            't'=>time(),
                            'remark'=>'二级用户推荐奖励'.$jl_price.'元',
                            'uid'=>$second_user_info['id']
                        );
                        M('user_income')->data($income_data)->add();
                        // 加入消息通知
                        M('user_message')->data(array('uid'=>$second_user_info['id'],'content'=>'二级用户推荐奖励'.$jl_price.'元','t'=>time(),'type'=>2))->add();
                    }
                }
            }
        }    
    }
    
    /**
     * 更新用户等级相关信息
     * @param number $order_id
     */
    private function updateUserLevelInfo($order_id=0)
    {
        $order_info = M('user_level_buy')->where('id='.$order_id)->find();
        // 计算该等级有效天数
        $level_info = M('user_level')->where('id='.$order_info['level_id'])->field('expri_day')->find();
        $days = intval($level_info['expri_day']);
        $data = array(
            'level_id'=>$order_info['level_id'],
            'expri_day'=>date("Y-m-d",strtotime("$days day"))
        );
        //更新数据库
        M('user')->data($data)->where('id='.$order_info['uid'])->save();
        // 加入消息通知
        $user = M('user')->where('id='.$order_info['uid'])->find();
        M('user_message')->data(array('uid'=>$user['id'],'content'=>'成功开通会员等级'.$level_info['title'],'t'=>time(),'type'=>2))->add();
        //更新上级邀请人会员团队等级信息
        $this->updateParentUserTeamInfo($user['pid']);
    }
    
    
    /**
     * 更新上级会员团队等级信息
     * @param number $uid
     */
    private function updateParentUserTeamInfo($uid=0)
    {
        if($uid){
            //已成功推广会员数量
            $countSql = "select count(*) as total_num from dz_user a where a.pid='{$uid}' and a.id in (select b.uid from dz_user_level_buy b where b.`status`=2 group by b.uid)";
            $countQuery = M()->query($countSql);
            $tg_num = $countQuery[0]['total_num'];
            $user = M('user')->where('id='.$uid)->find();
            if($user['team_level']){
                $team_level = M('team_level')->where(array('name'=>$user['team_level']))->find();
                $team_next_level = M('team_level')->where(array('o'=>array('gt',$team_level['o'])))->limit(1)->order('o asc')->select();
                if(!empty($team_next_level)){
                    //判断是否满足升级条件
                    $min_num = $team_next_level[0]['min_num'];
                    if(intval($tg_num) >= intval($min_num) && intval($team_next_level[0]['user_level_id']) > intval($user['level_id'])){
                        // 计算该等级有效天数
                        $level_info = M('user_level')->where('id='.$team_next_level[0]['user_level_id'])->field('expri_day,title')->find();
                        $days = intval($level_info['expri_day']);
                        $data = array(
                            'level_id'=>$team_next_level[0]['user_level_id'],
                            'expri_day'=>date("Y-m-d",strtotime("$days day")),
                            'team_level'=>$team_next_level[0]['name']
                        );
                        M('user')->data($data)->where('id='.$uid)->save();
                        //加入消息通知
                        M('user_message')->data(array('uid'=>$uid,'content'=>'团队等级升级为'.$team_next_level[0]['name'],'t'=>time(),'type'=>2))->add();
                    }
                }
            }else{
                $team_next_level = M('team_level')->where(array('o'=>1))->find();
                $min_num = $team_next_level['min_num'];
                if(intval($tg_num) >= intval($min_num) && intval($team_next_level['user_level_id']) > intval($user['level_id'])){
                    // 计算该等级有效天数
                    $level_info = M('user_level')->where('id='.$team_next_level['user_level_id'])->field('expri_day,title')->find();
                    $days = intval($level_info['expri_day']);
                    $data = array(
                        'level_id'=>$team_next_level['user_level_id'],
                        'expri_day'=>date("Y-m-d",strtotime("$days day")),
                        'team_level'=>$team_next_level['name']
                    );
                    M('user')->data($data)->where('id='.$uid)->save();
                    //加入消息通知
                    M('user_message')->data(array('uid'=>$uid,'content'=>'团队等级升级为'.$team_next_level['name'],'t'=>time(),'type'=>2))->add();
                }
            }
        }
    }
}
